﻿using System;
using System.CodeDom;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using MusicStore.Data.Repository;
using MusicStore.Entities;
using NUnit.Framework;

namespace MusicStore.Data.Test.Repository
{
	[TestFixture]
	public class AlbumRepositoryTest : TestBase
	{
		private readonly AlbumRepository _repository = new AlbumRepository();

		[SetUp]
		public void TestSetup()
		{
			_repository.Session.BeginTransaction();
		}

		[TearDown]
		public void TestTearDown()
		{
			_repository.Session.Transaction.Rollback();
		}

		[Test]
		public void SaveAlbum()
		{
			CodeTypeReference cr = new CodeTypeReference(typeof(ClientBase<>));
			// maybe it's better to use an attribute syntax
			CreateDatabase();

			Album album = CreateTestAlbum(0);
			_repository.Save(album);
         Album loaded = _repository.Albums().ByAlbumId(album.Id);
			Assert.IsNotNull(loaded);
			Assert.AreEqual(album.Tracks.Count, loaded.Tracks.Count);
		}

		/// <summary>
		/// create and save a series of albums
		/// </summary>
		[Test]
		public void SaveAlbums()
		{
			// maybe it's better to use an attribute syntax
			CreateDatabase();

			List<Album> albums = CreateTestAlbums();
			albums.ForEach(_repository.Save);

			// load albums
			int count = _repository.Albums().Count();
			Assert.That(count == 10);
			Album loaded = _repository.Albums().Where(a => a.Title == "Title1").FirstOrDefault();
			Assert.IsNotNull(loaded);
			loaded = _repository.Albums().Where(a => a.Title == "NonExistant").FirstOrDefault();
			Assert.IsNull(loaded);

			// load some album summaries
			count = _repository.AlbumSummaries().Count();
			Assert.That(count == 10);
			AlbumSummary loaded2 = _repository.AlbumSummaries().Where(a => a.Title == "Title1").FirstOrDefault();
			Assert.IsNotNull(loaded2);
			loaded2 = _repository.AlbumSummaries().Where(a => a.Title == "NonExistant").FirstOrDefault();
			Assert.IsNull(loaded2);

			// perform a search
			List<AlbumSummary> searchresult = _repository.AlbumSummaries().Search("Titl").ToList();
			Assert.IsNotEmpty(searchresult);
			Assert.AreEqual(searchresult.Count(), 10);
			searchresult = _repository.AlbumSummaries().Search("Author1").ToList();
			Assert.IsNotEmpty(searchresult);
			Assert.AreEqual(searchresult.Count(), 1);
		}

	}
}
